package com.weaver.qfengx.loader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Description 自定义classloader 以实现动态加载class
 * @Author Qfengx <qffg1998@126.com>
 * @Date 2021-08-07 16:37:22
 */
public class WeaverQfengxClassLoader extends ClassLoader {

    private byte[] bb = null;

    public WeaverQfengxClassLoader() {
        super(ClassLoader.getSystemClassLoader().getParent()); // 提升至与系统类加载器平级
    }

    public Class<?> loadClass(String name) throws ClassNotFoundException {
        return loadClass(name, false);
    }

    protected synchronized Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException {
        Class c = findLoadedClass(className);
        FileInputStream fis = null;
        if (c == null) {
            try {
                c = super.loadClass(className, resolve);
            } catch (ClassNotFoundException e) {
                try {
                    fis = new FileInputStream("bin\\" + className + ".class");
                    int length = 0;
                    length = fis.available();
                    bb = new byte[length];
                    fis.read(bb);
                    fis.close();
                } catch (FileNotFoundException fe) {
                    throw new ClassNotFoundException("所要加载的类的字节码文件不存在");
                } catch (IOException ie) {
                    throw new RuntimeException("加载字节码文件时出错");
                }
                c = defineClass(className, bb, 0, bb.length);//createClass(className);
            }
        }
        if (resolve) {
            resolveClass(c);
        }
        return c;
    }

    public Class createClass(String className) {
        Class clazz = defineClass(className, bb, 0, bb.length);
        if (clazz ==null)
            System.out.println(className + " is null");
        return clazz;
    }

}
